﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CNative.Dapper.Utils
{
    public enum DbObjectType
    {
        Table = 0,
        View = 1,
        All = 2
    }
    /// <summary>
    /// 数据库所有表的信息
    /// </summary>
    public class DbTableInfo
    {
        public DbObjectType DbObjectType { get; set; } = DbObjectType.Table;
        public string EntityName { get; set; }
        private string _DbTableName;
        /// <summary>
        /// 表名
        /// </summary>
        public string TableName { get { return _DbTableName == null ? EntityName : _DbTableName; } set { _DbTableName = value; } }
        public string Name { get { return TableName; } set { TableName = value; } }
        /// <summary>
        /// 库名
        /// </summary>
        public string Schema { get; set; }

        /// <summary>
        /// 表描述说明
        /// </summary>
        public string Description
        {
            get
            {
                return _description.IsNullOrEmpty() ? TableName : _description;
            }
            set
            {
                _description = value;
            }
        }

        private string _description { get; set; }
        public bool IsDisabledDelete { get; set; }
        public bool IsDisabledUpdateAll { get; set; }
        public List<DbColumnInfo> Columns { get; set; }

        public IEnumerable<DbColumnInfo> GetColumns(IEnumerable<string> names)
        {
            foreach (var name in names)
            {
                yield return GetColumn(name);
            }
        } 
        public IEnumerable<DbColumnInfo> GetColumns(params string[] names)
        {
            return GetColumns(names);
        }
        public DbColumnInfo GetColumn(string name)
        {
            var column = Columns?.FirstOrDefault(c => c.Name.Equals(name,StringComparison.OrdinalIgnoreCase));
            //if (column == null)
            //{
            //    throw new ArgumentException("column not found", name);
            //}
            return column;
        }

        public bool ExistsColumn(string name)
        {
            return Columns?.Exists(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase))== true;
        }
        /// <summary>
        /// 获取所有主键
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IEnumerable<DbColumnInfo> GetKeyColumns()
        {
            return Columns?.Where(x => x.IsPrimaryKey);
        }

    }
}
